###############################
# Polities: Descriptive plots and maps
#
# Replication Material for:
# Continuity or Change? (In)direct Rule in British and French Colonial Africa
# 
# Carl Mueller-Crepon, 2020
# International Organization
#
# File Description:
# Descriptive plots and maps
#
# Called from scripts/polities/analysis.R 
#
##################################



##############################################
# Plot: Ever reaches independence?
# Figure 4 Main Paper
##############################################

# Subset Data
plot.df <- aggregate.data.frame(list(independence = polity.yrs.df$action.type == "decolonization"),
                                polity.yrs.df[,c("polity","polity.id","countries_cowid","colbrit", "colfrnc")],
                                FUN = max, na.rm = T)
plot.df <- plot.df[plot.df$colbrit == 1 | plot.df$colfrnc == 1,]
plot.df <- plot.df[plot.df$polity.id %in% unique(polity.yrs.df$polity.id[polity.yrs.df$col.brit == 1 | polity.yrs.df$col.frnc == 1]),]

# Estimate linear model
m <- lm(independence ~ colbrit, plot.df)

# Print model summary (debug mode)
# summary(m)

# Predict survival rate
plot.df <- predict(m, data.frame(colbrit = c(0,1)), se.fit = T)
plot.df <- data.frame(coef = plot.df$fit,
                      se = plot.df$se.fit)
plot.df$pos <- c(1:nrow(plot.df))
plot.df$Colony <- c("French colony","British colony")

# Make plot
png(paste0(fig.path, "descr.plot.png"), width = 3, height = 3, unit = "in", res = 600)
g <- ggplot(plot.df, 
       aes(x = pos, y = coef, color = Colony)) + geom_point() + 
  geom_errorbar(aes(ymin = coef - 1.96*se, 
                    ymax = coef + 1.96*se), 
                width=.1) +
  geom_hline(yintercept = 0, color = "darkgrey", lty = 2) + 
  ylab("Fraction to reach independence") + xlab("") +
  scale_color_manual(breaks=c("British colony","French colony"),
                     values = c(`British colony` = "red", `French colony`  = "blue")) +
  scale_x_continuous(breaks = c(1,2), label = c("French rule", "British rule"), limits = c(.5,2.5))  + 
  theme(legend.position="none")
print(g)
dev.off()

########################################
# Life of some polities
# Figure 2 in main paper
########################################

# Which polities?
plot.polities <- rev(c( "Dagomba", "Nkore", "Potiskum",
                        "Dahomey","Futa Jallon", "Wadai"))
plot.labels <- rev(c( "Dagomba (GHA)", "Nkore (UGA)", "Potiskum (NGA)",
                      "Dahomey (BEN)","Futa Jallon (GIN)", "Wadai (TCD)"))
year.range <- c(1800:2006)

# Plot.df
plot.df <- polity.yrs.df[!is.na(polity.yrs.df$polity) & polity.yrs.df$polity %in% plot.polities & polity.yrs.df$year %in% year.range,]

# IDs for polities
plot.df$pol.id <- NA
for(p in c(1:length(plot.polities))){
  plot.df$pol.id[plot.df$polity == plot.polities[p]] <- p
}

# IDs for rulers
plot.df <- join(plot.df, ruler.yrs.df[,c("year","polity.id","ruler.id")],
                type = "left", match = "first")
uni.rulers <- na.omit(unique(plot.df$ruler.id))
plot.df$rul.id <- 3
for(p in c(1:length(uni.rulers))){
  plot.df$rul.id[plot.df$ruler.id == uni.rulers[p]] <- as.numeric(p %% 2 == 0) + 1
}
plot.df$rul.id <- as.character(plot.df$rul.id)

# Colony label
plot.df$Colony <- ifelse(plot.df$col.brit == 1, "British colony",
                         ifelse(plot.df$col.frnc == 1, "French colony", NA))

# Colonial power data ##
col.df <-  aggregate(list(start.year = plot.df$year[plot.df$col.brit == 1 | plot.df$col.frnc == 1]),
                     plot.df[plot.df$col.brit == 1 | plot.df$col.frnc == 1,c("countries_cowid", "ind.year", "pol.id", "Colony", "polity")],
                     FUN = min)

# Plot
png(paste0(fig.path, "polity_life.png"), width = 7, height = 2, unit = "in", res = 600)
g <- ggplot() + 
  geom_rect(data = col.df, 
            aes(xmin = start.year - .5, xmax = ind.year + .5, ymax = pol.id + .25, ymin = pol.id - .25, 
                col = Colony, fill = Colony)) +
  geom_rect(data = plot.df, aes(xmin = year - .5, xmax = year + .5, ymax = pol.id + .15, ymin = pol.id - .15, 
                                col = "1", fill = "1")) +
  scale_fill_manual(breaks=c("British colony","French colony"),
                    values = c(`British colony` = "red", `French colony`  = "blue",`1` = "darkgrey", `2` = "grey",`3` =  "lightgrey")) +
  scale_color_manual(breaks=c("British colony","French colony"),
                     values = c(`British colony` = "red", `French colony`  = "blue",`1` = "darkgrey", `2` = "grey",`3` =  "lightgrey")) +
  scale_y_continuous(breaks = col.df$pol.id, label = unlist(lapply(col.df$polity, function(p){plot.labels[plot.polities == p]}))) +
  theme(text = element_text(size=15))
print(g)
dev.off()



########################################
# MAP WEST AFRICA, First year of colonization
# Figure 3 Main Paper
########################################

# Plot locals
point.size <- 1.25


# ... country-codes
west.africa <- c(402:475,482,483)

# ... ever colonized polities
ever.colonized <- polity.yrs.df$polity.id[polity.yrs.df$polity.id %in% unique(polity.yrs.df$polity.id[rowSums(polity.yrs.df[,paste0("col.",c("brit", "frnc"))], na.rm=T) > 0])]
these.polity.yrs <- polity.yrs.df[!is.na(polity.yrs.df$x) & !is.na(polity.yrs.df$y) & 
                                    polity.yrs.df$action.type != "decolonization" & 
                                    polity.yrs.df$polity.id %in% ever.colonized &
                                    polity.yrs.df$countries_cowid %in% west.africa &
                                    (polity.yrs.df$col.brit == 1 | polity.yrs.df$col.frnc == 1), ]
points <- data.frame(do.call(rbind,
                             lapply(unique(these.polity.yrs$polity.id), function(p){
                               x <- these.polity.yrs[these.polity.yrs$colonized & these.polity.yrs$polity.id == p,]
                               x[x$year == min(x$year, na.rm = T),]
                             })), stringsAsFactors = F)
points[points$countries_cowid == 461,c("year","start.min","end.max","polity", "col.brit", "col.frnc")]

# ... subset murdock
map.ext <- extent(murdock.cow.spdf[murdock.cow.spdf$countries_cowid %in% west.africa,])
map.ext[c(2,4)] <- map.ext[c(2,4)] - c(3,2)
murdock.plot <- raster::crop(murdock.cow.spdf,
                             map.ext)

# ... reconstruct colony borders
col.borders <- gUnaryUnion(murdock.plot, id = murdock.plot$cowid)

# ... All Africa
library(cshapes)
all.africa <- cshp(date = as.Date("2000-01-01"))
all.africa <- all.africa[!all.africa$COWCODE %in% c(580, 581, 590, 402) & all.africa$COWCODE %in% c(402:626, 651),]
all.africa <- gUnaryUnion(all.africa, id = rep(1, length(all.africa)))

# ... plot
png(paste0(fig.path, "polity_mapwa.png"), width = 6.5, height = 4, unit = "in", res = 600)
par(mar = c(0,0,0,0))
plot(murdock.plot, col = grey(seq(.75,.25,length.out = 4))[murdock.plot$v33.num +1],
     ylim = c(extent(murdock.plot)[3]-2,extent(murdock.plot)[4]),
     xlim = c(map.ext[1] -1, map.ext[2] + 9))
plot(col.borders, border = "white", lwd = 2, add = T)
points(points[,c("x","y")], col = "white", pch = 19, cex = point.size + .25)
points(points[,c("x","y")], col = c("blue", "red")[points$col.brit + 1], pch = 1, cex = point.size)
points(points[!points$polity.id %in% polity.yrs.df$polity.id[polity.yrs.df$action.type == "decolonization"],c("x","y")],
       col = c("blue", "red")[points$col.brit[!points$polity.id %in% polity.yrs.df$polity.id[polity.yrs.df$action.type == "decolonization"]] + 1], pch = 4, cex = point.size - 0.5)

# ... add markers for selected polities
mark.polity <- c( "Dagomba",  "Potiskum","Dahomey","Futa Jallon", "Wadai")

mark.coord <- points[points$polity %in% mark.polity, c("x","y")]
aim.coord <- mark.coord

aim.coord$x <- aim.coord$x + c(-8,+2,-3,0,+4)
aim.coord$y <- aim.coord$y + c(-6.26,-4,0,+14,0)
segments(mark.coord$x, mark.coord$y, aim.coord$x,aim.coord$y, col = c("blue", "red")[points$colbrit[points$polity %in% mark.polity]+1])

text(aim.coord, label = unlist(lapply(points$polity[points$polity %in% mark.polity], function(p){plot.labels[plot.polities == p]})), 
     pos = c(1,1,2,3,4), offset = 0.3,
     col = c("blue", "red")[points$col.brit[points$polity %in% mark.polity]+1], cex = .9)

# ... legend
legend(-25, extent(murdock.plot)[3]-1, # places a legend at the appropriate place 
       c("State","Large chiefdoms","Petty chiefdoms","Acephalous society","Missing"), # puts text in the legend
       fill = c(grey(seq(.25,.75,length.out = 4)), "white"), cex = 0.65, border = c(rep(NA,4),"black"), bty = "n",
       ncol = 5)


# calculate position of inset
plotdim <- par("plt")
xleft    = plotdim[1] + (plotdim[2] - plotdim[1]) * 0.0
xright   = plotdim[1] + (plotdim[2] - plotdim[1]) * 0.18 #
ybottom  = plotdim[2] - (plotdim[4] - plotdim[3]) * 0.3 #
ytop     = plotdim[2] - (plotdim[4] - plotdim[3]) * 0.1 #

# set position for inset
par(fig = c(xleft, xright, ybottom, ytop) , mar=c(0,0,0,0) , new=TRUE)
plot(all.africa, axes=FALSE, xlab="", ylab="", border = "grey", ylim = c(-34, 37.34041))
plot(as(extent(col.borders), "SpatialPolygons"), axes=FALSE, xlab="", ylab="",bg = "transparent",
     add = T)
dev.off()


########################################
# MAP ALL AFRICA, First year of colonization
# Appendix Figure A1
########################################

# Plot locals
point.size <- 1.25

# ... ever colonized polities
ever.colonized <- polity.yrs.df$polity.id[polity.yrs.df$polity.id %in% unique(polity.yrs.df$polity.id[rowSums(polity.yrs.df[,paste0("col.",c("brit", "frnc"))], na.rm=T) > 0])]
these.polity.yrs <- polity.yrs.df[!is.na(polity.yrs.df$x) & !is.na(polity.yrs.df$y) & 
                                    polity.yrs.df$action.type != "decolonization" & 
                                    polity.yrs.df$polity.id %in% ever.colonized &
                                    !is.na(polity.yrs.df$countries_cowid) &
                                    (polity.yrs.df$col.brit == 1 | polity.yrs.df$col.frnc == 1), ]
points <- data.frame(do.call(rbind,
                             lapply(unique(these.polity.yrs$polity.id), function(p){
                               x <- these.polity.yrs[these.polity.yrs$colonized & these.polity.yrs$polity.id == p,]
                               x[x$year == min(x$year, na.rm = T),]
                             })), stringsAsFactors = F)

# ... subset murdock
murdock.plot <- murdock.cow.spdf

# ... reconstruct colony borders
col.borders <- gUnaryUnion(murdock.plot, id = murdock.plot$cowid)

# ... reconstruct murdock borders
murdock.plot <- murdock.plot[murdock.plot$countries_cowid %in% na.omit(these.polity.yrs$countries_cowid), ]
eth.borders <- gUnaryUnion(murdock.plot, id = murdock.plot$gid)

# ... plot
png(paste0(fig.path, "polity_mapafrica.png"), width = 6, height = 5, unit = "in", res = 600)
par(mar = c(0,0,0,0))
plot(murdock.plot, col = grey(seq(.75,.25,length.out = 5))[murdock.plot$v33.num +1])

plot(col.borders, border = "white", lwd = 1, add = T)
plot(col.borders[!as.numeric(row.names(col.borders)) %in% na.omit(these.polity.yrs$countries_cowid), ], border = "grey", lwd = 1, add = T)
plot(eth.borders, col = NULL, add = T)
points(points[,c("x","y")], col = "white", pch = 19, cex = point.size)
points(points[,c("x","y")], col = c("blue", "red")[points$col.brit + 1], pch = 1, cex = point.size)
points(points[!points$polity.id %in% polity.yrs.df$polity.id[polity.yrs.df$action.type == "decolonization"],c("x","y")],
       col = c("blue", "red")[points$col.brit[!points$polity.id %in% polity.yrs.df$polity.id[polity.yrs.df$action.type == "decolonization"]] + 1], pch = 4, cex = point.size - 0.5)

# ... legend
legend(-20, -15, # places a legend at the appropriate place 
       c("Large state","State","Large chiefdoms","Petty chiefdoms","Acephalous society","Missing / not in sample"), # puts text in the legend
       fill = c(grey(seq(.25,.75,length.out = 5)), "white"), cex = 0.85, border = c(rep(NA,5),"black"), bty = "n")
dev.off()

